package com.property.demo.controller;

import com.property.demo.dto.ApiResponse;
import com.property.demo.model.Activity;
import com.property.demo.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@CrossOrigin
@RequestMapping("/api/activities")
public class ActivityController {

    @Autowired
    private ActivityService activityService;

    // 获取所有活动（分页）
    @GetMapping
    public ResponseEntity<?> getAllActivities(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long communityId,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String status) {
        
        try {
            Pageable pageable = PageRequest.of(page, size, Sort.by("id").descending());
            
            Page<Activity> activitiesPage;
            if (communityId != null || (title != null && !title.isEmpty()) || (status != null && !status.isEmpty())) {
                activitiesPage = activityService.findByFilters(communityId, title, status, pageable);
            } else {
                activitiesPage = activityService.findAll(pageable);
            }
            
            return ResponseEntity.ok(activitiesPage);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 获取所有活动（不分页）
    @GetMapping("/all")
    public ResponseEntity<?> getAllActivitiesNoPage() {
        try {
            List<Activity> activities = activityService.findAll();
            return ResponseEntity.ok(activities);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 根据ID获取活动
    @GetMapping("/{id}")
    public ResponseEntity<?> getActivityById(@PathVariable Long id) {
        try {
            Optional<Activity> activity = activityService.findById(id);
            if (activity.isPresent()) {
                return ResponseEntity.ok(activity.get());
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 创建活动
    @PostMapping
    public ResponseEntity<?> createActivity(@RequestBody Activity activity) {
        try {
            Activity savedActivity = activityService.save(activity);
            return ResponseEntity.ok(new ApiResponse(true, "活动创建成功", savedActivity));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 更新活动
    @PutMapping("/{id}")
    public ResponseEntity<?> updateActivity(@PathVariable Long id, @RequestBody Activity activityDetails) {
        try {
            Activity updatedActivity = activityService.update(id, activityDetails);
            if (updatedActivity != null) {
                return ResponseEntity.ok(new ApiResponse(true, "活动更新成功", updatedActivity));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 删除活动
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteActivity(@PathVariable Long id) {
        try {
            Optional<Activity> activity = activityService.findById(id);
            if (activity.isPresent()) {
                activityService.delete(id);
                return ResponseEntity.ok(new ApiResponse(true, "活动删除成功"));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }
    
    // 批量删除活动
    @DeleteMapping("/batch")
    public ResponseEntity<?> batchDeleteActivities(@RequestBody List<Long> ids) {
        try {
            activityService.deleteAll(ids);
            return ResponseEntity.ok(new ApiResponse(true, "活动批量删除成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }
    
    // 根据小区ID获取活动
    @GetMapping("/community/{communityId}")
    public ResponseEntity<?> getActivitiesByCommunity(@PathVariable Long communityId) {
        try {
            List<Activity> activities = activityService.findByCommunityId(communityId);
            return ResponseEntity.ok(activities);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }
    
    // 根据标题搜索活动
    @GetMapping("/search")
    public ResponseEntity<?> searchActivities(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String status) {
        try {
            List<Activity> activities;
            if (title != null && !title.isEmpty()) {
                activities = activityService.findByTitleContaining(title);
            } else if (status != null && !status.isEmpty()) {
                activities = activityService.findByStatus(status);
            } else {
                activities = activityService.findAll();
            }
            return ResponseEntity.ok(activities);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 健康检查接口
    @GetMapping("/ping")
    public ResponseEntity<String> ping() {
        return ResponseEntity.ok("pong");
    }
} 